<?php


namespace app\common\service;


use think\Db;
use think\Exception;

class RefundService extends Service
{
    protected $tableName = 'sms_mk_orders';

    protected $orderId;

    protected $userOder;

    public function __construct($orderId,$userId=null,$param = null)
    {
        $this->orderId = $orderId;
        parent::__construct($param);
        $this->db->where('id','=',$orderId);
        if($userId){//加强验证订单信息
            $this->where('sms_users_id','=',$userId);
        }
        $this->userOder = $this->db->find();
        if(!$this->userOder)throw new Exception('订单信息不存在了');
        if($this->userOder['state'] != 'refund'){
            throw new Exception('订单状态不对，不能退款');
        }
    }

    public function refundMoney(){

        $mchid = config("weChat")['mch_id'];     //微信支付商户号 PartnerID 通过微信支付商户资料审核后邮件发送
        $appid =config("weChat")['appid']; //微信支付申请对应的公众号的APPID
        $apiKey = config('weChat')['key'];  //https://pay.weixin.qq.com 帐户设置-安全设置-API安全-API密钥-设置API密钥
        $orderNo = $this->userOder['number'];           //商户订单号（商户订单号与微信订单号二选一，至少填一个）
        $wxOrderNo = $this->userOder['pay_number'];           //微信订单号（商户订单号与微信订单号二选一，至少填一个）
        $totalFee =$this->userOder['total_fee'];          //订单金额
        $refundFee = $this->userOder['total_fee'];         //退款金额
        $refundNo = createOrderNumber($this->orderId,'RF');    //退款订单号(可随机生成)
        $Wxrefund = new \app\common\service\WxpayService($mchid,$appid,$apiKey);
        $result=  $Wxrefund->doRefund($totalFee,$refundFee,$refundNo,$wxOrderNo,$orderNo);
        if($result['data']=='SUCCESS'){

            $data['state']='refunded';//申请退款中
            $data['refund_money'] = $refundFee;
            $data['refund_number'] = $refundNo;
            $data['refund_time']=time();
            $res = Db::table('sms_mk_orders')
                ->where('id','=',$this->orderId)
                ->update($data);
            if($res){
                return '退款成功';
            }else{
                throw new Exception('退款失败,请截图保留证据，第一时间联系工作人员!');
            }

        }
        throw new Exception('退款失败');
    }

}